﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using OneSoft.Web.UI.WebControls;

namespace BySoft.Web.Utility
{

    #region grid模块类型
    public enum FieldType
    {
        BoundField = 1,
        CheckBoxField = 2,
        CommandField = 3,
        ButtonField = 4,
        HyperLinkField = 5,
        ImageField = 6,
        CheckBoxExField = 7,
        DialogButtonTemplate = 8
    }
    #endregion

    #region GridColumn
    [Serializable]
    public class GridColumn
    {
        #region 变量
        public Unit unit;//宽度
        public string headerName;//标题
        public string fieldName;//绑定字段
        public FieldType type;//列类型
        public ButtonType button;//按钮类型
        public string commandName;
        public HorizontalAlign hAlign;//水平对齐
        public DialogButtonTemplate _dialogButtonTemplate;
        #endregion

        #region 构造函数
        public GridColumn(string headerName, string fieldName, Unit unit, FieldType type, ButtonType button, string commandName, HorizontalAlign hAlign)
        {
            this.headerName = headerName;
            this.fieldName = fieldName;
            this.unit = unit;
            this.type = type;
            this.button = button;
            this.commandName = commandName;
            this.hAlign = hAlign;
        }
        public GridColumn(DialogButtonTemplate dialogButtonTemplate)
        {
            _dialogButtonTemplate = dialogButtonTemplate;
        }
        #endregion
    }
    #endregion

    #region MyRegion
    public class GridHelper
    {
        #region 变量
        private GridView m_Grid;
        private List<GridColumn> columns = null;
        private bool isCheckBox = false;

        #endregion

        #region 构造函数
        public GridHelper(SGridView gridView, bool isPaged)
        {
            //for (int i = gridView.Columns.Count - 1; i >= 0; i--)
            //{
            //    gridView.Columns.RemoveAt(i);
            //}
            gridView.Columns.Clear();
            m_Grid = gridView;
            columns = new List<GridColumn>();
            SetGrid(isPaged);
        }
        #endregion

        #region SetGrid
        public void SetGrid(bool isPaged)
        {
            m_Grid.AutoGenerateColumns = false;
            m_Grid.PageSize = SystemConfig.PageSize;
            m_Grid.AllowPaging = isPaged;
            m_Grid.AllowSorting = isPaged;
        }
        #endregion

        #region AddColumn
        /// <summary>
        /// 增加支持全选的CheckBox
        /// </summary>
        /// <param name="type"></param>
        public void AddColumn(FieldType type)
        {
            AddColumn("", "", Unit.Pixel(20), type, ButtonType.Button, "", HorizontalAlign.Left);
        }

        /// <summary>
        /// 增加BoundField
        /// </summary>
        /// <param name="headerName">列标题</param>
        /// <param name="fieldName">列名</param>
        public void AddColumn(string headerName, string fieldName)
        {
            AddColumn(headerName, fieldName, Unit.Empty, FieldType.BoundField, ButtonType.Button, "", HorizontalAlign.Left);
        }

        /// <summary>
        /// 增加CheckField
        /// </summary>
        /// <param name="headerName"></param>
        /// <param name="fieldName"></param>
        /// <param name="unit"></param>
        /// <param name="type"></param>
        public void AddColumn(string headerName, string fieldName, Unit unit, FieldType type)
        {
            AddColumn(headerName, fieldName, unit, type, ButtonType.Button, "", HorizontalAlign.Center);
        }

        /// <summary>
        /// 增加BoundField
        /// </summary>
        /// <param name="headerName">列标题</param>
        /// <param name="fieldName">列名</param>
        /// <param name="unit">宽度</param>
        public void AddColumn(string headerName, string fieldName, Unit unit)
        {
            AddColumn(headerName, fieldName, unit, FieldType.BoundField, ButtonType.Button, "", HorizontalAlign.Left);
        }

        /// <summary>
        /// 增加BoundField
        /// </summary>
        /// <param name="headerName">列标题</param>
        /// <param name="fieldName">列名</param>
        /// <param name="unit">宽度</param>
        /// <param name="hAlign">水平对齐</param>
        public void AddColumn(string headerName, string fieldName, Unit unit, HorizontalAlign hAlign)
        {
            AddColumn(headerName, fieldName, unit, FieldType.BoundField, ButtonType.Button, "", hAlign);
        }

        /// <summary>
        /// 增加BoundField
        /// </summary>
        /// <param name="headerName">列标题</param>
        /// <param name="fieldName">列名</param>
        /// <param name="unit">宽度</param>
        /// <param name="type">field类型</param>
        /// <param name="button">button类型</param>
        /// <param name="commandName"></param>
        /// <param name="hAlign">水平对齐</param>
        public void AddColumn(string headerName, string fieldName, Unit unit, FieldType type, ButtonType button, string commandName, HorizontalAlign hAlign)
        {
            string headerNameTemp = headerName;
            //headerNameTemp = headerNameTemp.Replace(":", "").Replace("：", "");
            GridColumn column = new GridColumn(headerNameTemp, fieldName, unit, type, button, commandName, hAlign);
            columns.Add(column);
        }

        /// <summary>
        /// 增加ButtonField
        /// </summary>
        /// <param name="headerName">列标题</param>
        /// <param name="fieldName">按钮名称或者图片按钮路径</param>
        /// <param name="commandName">命令名称</param>
        public void AddColumn(string headerName, string fieldName, string commandName)
        {
            AddColumn(headerName, fieldName, ButtonType.Image, commandName, HorizontalAlign.Center);
        }

        /// <summary>
        /// 增加ButtonField
        /// </summary>
        /// <param name="headerName">列标题</param>
        /// <param name="fieldName">按钮名称或者图片按钮路径</param>
        /// <param name="commandName">命令名称</param>
        public void AddColumn(string headerName, string fieldName, string commandName, Unit unit)
        {
            AddColumn(headerName, fieldName, ButtonType.Image, commandName, HorizontalAlign.Center);
        }

        /// <summary>
        /// 增加ButtonField
        /// </summary>
        /// <param name="headerName">列标题</param>
        /// <param name="fieldName">按钮名称或者图片按钮路径</param>
        /// <param name="button">按钮类型</param>
        /// <param name="commandName">命令名称</param>
        public void AddColumn(string headerName, string fieldName, ButtonType button, string commandName, HorizontalAlign hAlign)
        {
            string headerNameTemp = headerName;
            //headerNameTemp = headerNameTemp.Replace(":", "").Replace("：", "");
            GridColumn column = new GridColumn(headerNameTemp, fieldName, Unit.Pixel(SystemConfig.BtnLength), FieldType.ButtonField, button, commandName, hAlign);
            columns.Add(column);
        }

        public void AddColumn(string headerName, IDictionary<string, string> dataField, string dialogTitle, string dialogUrl, string closedCallBack, int dialogWidth, int dialogHeight, string imageUrl)
        {
            DialogButtonTemplate dialogButtonTemplate = new DialogButtonTemplate(dataField);
            dialogButtonTemplate.DialogWidth = dialogWidth;
            dialogButtonTemplate.DialogHeight = dialogHeight;
            dialogButtonTemplate.DialogTitle = dialogTitle;
            dialogButtonTemplate.DialogURL = dialogUrl;
            dialogButtonTemplate.ClosedCallBack = closedCallBack;
            dialogButtonTemplate.ImageUrl = imageUrl;
            GridColumn column = new GridColumn(dialogButtonTemplate);
            column.unit = Unit.Pixel(SystemConfig.BtnLength);
            column.hAlign = HorizontalAlign.Center;
            column.headerName = headerName;
            column.type = FieldType.DialogButtonTemplate;
            columns.Add(column);
        }
        #endregion

        #region InitGridColumn
        /// <summary>
        ///　根据添加的列信息初始化GridView的Column
        /// </summary>
        public void InitGridColumn()
        {
            foreach (GridColumn column in columns)
            {
                FieldType type = column.type;
                switch (type)
                {
                    case FieldType.BoundField:
                        BoundField bf = new BoundField();
                        bf.HeaderText = column.headerName;
                        bf.HeaderStyle.Width = column.unit;
                        bf.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                        bf.DataField = column.fieldName;
                        bf.ItemStyle.Width = column.unit;
                        bf.ItemStyle.HorizontalAlign = column.hAlign;
                        bf.SortExpression = column.fieldName;
                        m_Grid.Columns.Add(bf);
                        break;
                    case FieldType.ButtonField:
                        ButtonField btn = new ButtonField();
                        btn.HeaderText = column.headerName;
                        btn.HeaderStyle.Width = column.unit;
                        btn.HeaderStyle.Wrap = false;
                        btn.ButtonType = column.button;
                        btn.ItemStyle.Width = column.unit;
                        btn.ItemStyle.HorizontalAlign = column.hAlign;
                        if (btn.ButtonType == ButtonType.Image)
                        {
                            btn.ImageUrl = column.fieldName;
                        }
                        else
                        {
                            btn.Text = column.fieldName;
                        }
                        btn.CommandName = column.commandName;
                        m_Grid.Columns.Add(btn);
                        break;
                    case FieldType.CheckBoxExField:
                        isCheckBox = true;
                        TemplateField tf = new TemplateField();
                        HeaderCheckBoxTemplate header = new HeaderCheckBoxTemplate();
                        tf.HeaderTemplate = header;
                        CheckBoxTemplate cb = new CheckBoxTemplate();
                        tf.ItemTemplate = cb;
                        tf.ItemStyle.Width = column.unit;
                        tf.ItemStyle.HorizontalAlign = column.hAlign;
                        tf.HeaderStyle.Width = column.unit;
                        m_Grid.Columns.Add(tf);
                        break;
                    case FieldType.CheckBoxField:
                        CheckBoxField cbf = new CheckBoxField();
                        cbf.HeaderText = column.headerName;
                        cbf.DataField = column.fieldName;
                        cbf.ItemStyle.HorizontalAlign = column.hAlign;
                        m_Grid.Columns.Add(cbf);
                        break;
                    case FieldType.HyperLinkField:
                        HyperLinkField hf = new HyperLinkField();
                        hf.Text = column.headerName;
                        hf.ItemStyle.HorizontalAlign = column.hAlign;
                        m_Grid.Columns.Add(hf);
                        break;

                    case FieldType.DialogButtonTemplate:
                        {
                            DialogButtonTemplate dialogButtonTemplate = column._dialogButtonTemplate;
                            TemplateField templateField = new TemplateField();
                            templateField.ItemTemplate = dialogButtonTemplate;
                            templateField.HeaderText = column.headerName;
                            templateField.HeaderStyle.Width = templateField.ItemStyle.Width = column.unit;
                            templateField.HeaderStyle.HorizontalAlign = templateField.ItemStyle.HorizontalAlign = column.hAlign;


                            m_Grid.Columns.Add(templateField);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        #endregion

        #region ItemTemplateGenerate
        /// <summary>
        /// 重新产生模版列
        /// </summary>
        /// <param name="e"></param>
        protected void ItemTemplateGenerate(GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (isCheckBox)
                {
                    CheckBox cb = new CheckBox();
                    cb.ID = "KeyCBHeader";
                    cb.Attributes.Add("onclick", "GridSelectAll(this);");
                    e.Row.Cells[0].Controls.Add(cb);
                }
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (isCheckBox)
                {
                    CheckBox cb = new CheckBox();
                    cb.ID = "KeyCB";
                    e.Row.Cells[0].Controls.Add(cb);
                }
            }
        }
        #endregion

        #region 绑定空表头
        /// <summary>
        /// 应用GridView DataBind 如果数据为空的话会默认 绑定 表头
        /// </summary>
        /// <param name="grid"></param>
        public static void DataBind(SGridView grid)
        {
            if (grid.DataSource != null
                  && grid.DataSource is DataTable
                  && ((DataTable)(grid.DataSource)).Rows.Count > 0)
            {
                grid.DataBind();
            }
            else
            {
                grid.DataBind();
                UIHelper.BindNullSGridView(grid);
            }
        }
        public static int GetPageTotal(SGridView grid)
        {
            if (grid.DataSource != null
                     && grid.DataSource is DataTable
                     && ((DataTable)(grid.DataSource)).Rows.Count > 0)
            {
                if (((DataTable)(grid.DataSource)).Rows.Count == 1 && grid.Rows.Count == 0)
                {
                    return 0;
                }
                return ((DataTable)(grid.DataSource)).Rows.Count;
            }
            return 0;

        }
        #endregion
    }
    #endregion

    #region CheckBoxTemplate
    public class CheckBoxTemplate : ITemplate
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public CheckBoxTemplate()
        {
        }

        /// <summary>
        /// 添加CheckBox
        /// </summary>
        /// <param name="container"></param>
        public void InstantiateIn(Control container)
        {
            CheckBox cb = new CheckBox();
            cb.ID = "KeyCB";
            container.Controls.Add(cb);
        }
    }
    #endregion

    #region HeaderCheckBoxTemplate
    public class HeaderCheckBoxTemplate : ITemplate
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public HeaderCheckBoxTemplate()
        {
        }

        /// <summary>
        /// 添加CheckBox
        /// </summary>
        /// <param name="container"></param>
        public void InstantiateIn(Control container)
        {
            CheckBox cb = new CheckBox();
            cb.ID = "KeyCBHeader";
            cb.Attributes.Add("onclick", "GridSelectAll(this);");
            container.Controls.Add(cb);
        }
    }
    #endregion

    #region DialogButtonTemplate
    public class DialogButtonTemplate : ITemplate
    {

        private IDictionary<string, string> dataField = new Dictionary<string, string>();
        private string imgdataField = string.Empty;
        private IDictionary<string, string> imgUrlDictionary = new Dictionary<string, string>();
        private bool enable = true;
        private string enableDataField = string.Empty;
        private string linkDataField = string.Empty;
        private string dialogTitleDataField = string.Empty;

        public string DialogTitleDataField
        {
            get { return dialogTitleDataField; }
            set { dialogTitleDataField = value; }
        }

        public string EnableDataField
        {
            get { return enableDataField; }
            set { enableDataField = value; }
        }
        public string LinkDataField
        {
            get { return linkDataField; }
            set { linkDataField = value; }
        }
        public string ImgdataField
        {
            get { return imgdataField; }
            set { imgdataField = value; }
        }
        public IDictionary<string, string> ImgUrlDictionary
        {
            get { return imgUrlDictionary; }
            set { imgUrlDictionary = value; }
        }
        private string m_DialogURL = string.Empty;
        public string DialogURL
        {
            get { return DialogUrl_temp; }
            set { DialogUrl_temp = value; }
        }
        private string DialogUrl_temp = string.Empty;
        private string m_ImageUrl = string.Empty;
        private string m_ClosedCallBack = string.Empty;

        public string ClosedCallBack
        {
            get { return m_ClosedCallBack; }
            set { m_ClosedCallBack = value; }
        }
        public string ImageUrl
        {
            get { return m_ImageUrl; }
            set { m_ImageUrl = value; }
        }
        private int m_DialogWidth = 700;
        public int DialogWidth
        {
            get { return m_DialogWidth; }
            set { m_DialogWidth = value; }
        }
        private int m_DialogHeight = 400;
        public int DialogHeight
        {
            get { return m_DialogHeight; }
            set { m_DialogHeight = value; }
        }

        private string m_DialogTitle = string.Empty;
        public string DialogTitle
        {
            get { return m_DialogTitle; }
            set { m_DialogTitle = value; }
        }

        public DialogButtonTemplate(IDictionary<string, string> dataField)
        {
            this.dataField = dataField;
        }


        void ITemplate.InstantiateIn(Control container)
        {
            ImageButton dialogButtonView = new ImageButton();
            dialogButtonView.ID = container.ClientID;
            dialogButtonView.ImageUrl = m_ImageUrl;
            dialogButtonView.DataBinding += new EventHandler(dialogButtonView_DataBinding);
            // dialogButtonView.OnClientClick = "javascript:ShowDialogFrame(";
            //dialogButtonView.DialogWidth = m_DialogWidth;
            //dialogButtonView.DialogHeight = m_DialogHeight;
            //dialogButtonView.DialogTitle = m_DialogTitle;
            //dialogButtonView.ClosedCallBack = m_ClosedCallBack;
            // dialogButtonView.DialogURL = m_DialogURL;
            container.Controls.Add(dialogButtonView);

        }
        void dialogButtonView_DataBinding(object sender, EventArgs e)
        {
            ImageButton dialogImageButton = (ImageButton)sender;

            GridViewRow gvRow = (GridViewRow)dialogImageButton.NamingContainer;

            string strTemp = DialogURL;
            if (linkDataField != string.Empty)
            {
                object dataValueLink = DataBinder.Eval(gvRow.DataItem, linkDataField);
                if (dataValueLink != DBNull.Value)
                {
                    strTemp = dataValueLink.ToString();
                }
            }


            foreach (KeyValuePair<string, string> dataFieldkey in dataField)
            {
                object dataValue = DataBinder.Eval(gvRow.DataItem, dataFieldkey.Value);
                if (dataValue != DBNull.Value)
                {
                    try
                    {
                        strTemp = strTemp + dataFieldkey.Key + HttpContext.Current.Server.UrlEncode(dataValue.ToString());
                    }
                    catch (InvalidCastException)
                    {
                        throw new Exception("Specified DataField was not invalid to be casted into string type.");
                    }

                }
                else
                {
                    throw new Exception("Id must not Null");

                }
            }

            string tempImgUrl = m_ImageUrl;
            if (ImgdataField != string.Empty)
            {
                object dataValueImgUrl = DataBinder.Eval(gvRow.DataItem, imgdataField);
                if (dataValueImgUrl != DBNull.Value)
                {
                    if (imgUrlDictionary.ContainsKey(dataValueImgUrl.ToString()))
                    {
                        tempImgUrl = imgUrlDictionary[dataValueImgUrl.ToString()];
                    }
                }
            }
            bool tempEnable = enable;
            if (enableDataField != string.Empty)
            {
                object dataValueEnable = DataBinder.Eval(gvRow.DataItem, enableDataField);
                if (dataValueEnable != DBNull.Value)
                {
                    tempEnable = Convert.ToBoolean(dataValueEnable);
                }
            }

            string tempDialogTitle = m_DialogTitle;
            if (dialogTitleDataField != string.Empty)
            {
                object dataValueDialogTitle = DataBinder.Eval(gvRow.DataItem, dialogTitleDataField);
                if (dataValueDialogTitle != DBNull.Value)
                {
                    tempDialogTitle = dataValueDialogTitle.ToString() + "-" + m_DialogTitle;
                }
            }

            //dialogImageButton.DialogTitle = tempDialogTitle;
            dialogImageButton.ImageUrl = tempImgUrl;
            m_DialogURL = strTemp;
            //dialogImageButton.DialogURL = m_DialogURL;
            //dialogImageButton.Enabled = tempEnable;
            if (tempEnable)
                dialogImageButton.OnClientClick = "javascript:ShowDialogFrame(\"" + tempDialogTitle + "\",\"" + m_DialogURL + "\",\"" + m_ClosedCallBack + "\",\"" + m_DialogWidth + "\",\"" + m_DialogHeight + "\");return false;";
            dialogImageButton.Enabled = tempEnable;
        }

    }
    #endregion
}
